package cn.wangkai.peanut.db;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.wangkai.peanut.db.iface.IDb;


public class Db implements IDb {
	private static final Log logger = LogFactory.getLog(Db.class);
	private ComboPooledDataSource ds = null;
	private int dbtype = IDb.DB_SQLSERVER;
	private long lasttime = System.currentTimeMillis();
	private static Properties props;
	private static Map<String,String> maps = new HashMap<String, String>();

	static{
		try {
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("wkdb.properties");
			if(is==null){
				logger.debug("wkdb.properties not found in the classpath!");
			}else{
				props = new Properties();
				props.load(is);
				Set<Object> sets = props.keySet();
				for (Object key : sets) {
					maps.put(String.valueOf(key), String.valueOf(props.get(key)));
				}
			}
		} catch (FileNotFoundException e) {
			logger.debug("wkdb.properties not found in the classpath!");
		} catch (IOException e) {
			logger.debug("wkdb.properties file is error!"+e.getMessage());
		} catch (Exception e) {
			logger.debug("wkdb.properties file is error!"+e.getMessage());
		}
	}

	/**
	 * 连接池启
	 * @throws Exception
	 */
	public void VStartPool() {
		VStartPool(null);
	}

	public void VStartPool(String name){
		setDs(StartPool(name));
	}
	/**
	 * 得到数据库连接池
	 * @param defaultname
	 * @return
	 */
	public ComboPooledDataSource StartPool(String defalutname) {
		//获取数据源
		String DbName = this.getClass().getName();
		if(maps.containsKey(DbName)) defalutname = maps.get(DbName);
		logger.debug(this.getClass().getName()+" User "+defalutname);
		if(StringUtils.isBlank(defalutname))
			return new ComboPooledDataSource();
		else{
			return new ComboPooledDataSource(defalutname);
		}
	}
	
	public int getDbtype(int dbtype){
		String key = this.getClass().getName()+".dbtype";
		if(maps.containsKey(key)) dbtype = NumberUtils.toInt(maps.get(key),dbtype);
		return dbtype;
	}

	/**
	 * 释放连接
	 */
	public void ShutdownPool() {
		if(getDs() !=null){
			getDs().close();
		}
		lasttime = System.currentTimeMillis();
	}

	/**
	 * 获得数据库连
	 */
	public synchronized Connection getConnection() throws WKDbException  {
		try {
			if (getDs() == null) VStartPool();
			return getDs().getConnection();
		} catch (Exception e) {
			logger.error("获得连接失败:", e.fillInStackTrace());
			throw new WKDbException(e);
		}
	}
	
//	private int getDbtype(){
//		return getDbtype(dbtype);
//	}

	public void closeds() {
		ds.close();
		ds=null;
	}

	public void setDs(ComboPooledDataSource cds) {
		ds = cds;
	}

	public ComboPooledDataSource getDs() {
		return ds;
	}

	public long getLasttime() {
		return lasttime;
	}

	@Override
	public int getDbtype() {
		return getDbtype(dbtype);
	}

}
